package me.yangxy.learning.service;

import me.yangxy.learning.api.DirectoryService;
import me.yangxy.learning.api.vo.AddContentReq;
import me.yangxy.learning.api.vo.DirectoryItemVO;
import me.yangxy.learning.dao.DirectoryItemDao;
import me.yangxy.learning.dao.model.DirectoryItem;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class DirectoryServiceProvider implements DirectoryService {

    @Autowired
    private DirectoryItemDao directoryItemDao;

    @Override
    public void addContent(AddContentReq data) {
        DirectoryItem item = new DirectoryItem();
        item.setEnContent(data.getEnglishContent());
        item.setCnContent(data.getChineseContent());
        item.setCreateTime(new Date());
        directoryItemDao.save(item);
    }

    @Override
    public void addContents(List<AddContentReq> datas) {
        for (AddContentReq data : datas) {
            addContent(data);
        }
    }

    @Override
    public List<DirectoryItemVO> queryAllContent() {
       List<DirectoryItemVO> result = new ArrayList<>();
       List<DirectoryItem> list = directoryItemDao.findAll();

       if(ObjectUtils.isEmpty(list)){
           return result;
       }

       for (DirectoryItem directoryItem : list) {
           result.add(parseToBusinessVO(directoryItem));
       }

       return result;
    }

    @Override
    public DirectoryItemVO queryById(Integer id) {
        Optional<DirectoryItem> dbBean = directoryItemDao.findById(id);
        DirectoryItem bean = dbBean.orElse(new DirectoryItem());
        return parseToBusinessVO(bean);
    }

    private DirectoryItemVO parseToBusinessVO(DirectoryItem dbBean) {
        DirectoryItemVO vo = new DirectoryItemVO();
        BeanUtils.copyProperties(dbBean,vo);
        return vo;
    }
}
